<template>
  <div class="inspection-container-1">
    <!-- 搜索栏 -->
    <div class="sickness-page-form">
      <el-input
        style="width: 300px"
        placeholder="请输入模板名称"
        v-model="formData.templateName"
        :disabled="prescriptionData.activeName_1 != '1'"
      />
      <el-button
        type="primary"
        @click="addDepApi"
        v-if="prescriptionData.activeName_1 == '1'"
        >保存</el-button
      >
    </div>
    <div style="margin-top: 14px">
      <TagInput
        @add-tag="addTag"
        :recomScene="recomScene"
        :isNone="prescriptionData.activeName_1"
      />
    </div>
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <h3>处方医嘱</h3>
      <div class="action-buttons" v-if="prescriptionData.activeName_1 == '1'">
        <el-button type="primary" plain @click="setActiveType('1')">
          中西成药处方
        </el-button>
        <el-button type="primary" plain @click="setActiveType('3')">
          中药处方
        </el-button>
        <el-button type="primary" plain @click="setActiveType('2')">
          输液处方
        </el-button>
        <el-button type="primary" plain @click="setActiveType('4')">
          外治处方
        </el-button>
      </div>
    </div>
    <!-- 表格 -->
    <template v-for="(item, indexNum) in prescriptionTypeList" :key="indexNum">
      <div
        class="custom-table"
        v-if="item.rxType == '1'"
        style="border: 1px solid #e4e7ed; margin-top: 10px"
      >
        <!-- 成药处方一 -->
        <div>
          <template v-if="item.rxType == '1'">
            <div
              class="table-header"
              style="
                justify-content: space-between;
                padding: 0 16px;
                border-radius: 12px;
              "
            >
              <div class="header-cell" style="color: #000000">
                {{ item.rxName }}
              </div>
              <div
                class="header-cell"
                @click="removeRow_1(item, indexNum)"
                v-if="prescriptionData.activeName_1 == '1'"
              >
                <img src="@/assets/manage/icon_del_nor.svg" alt="" />
              </div>
            </div>
            <!-- 表头 -->
            <div class="table-header">
              <div
                class="header-cell"
                style="width: 60px; justify-content: center"
              >
                序号
              </div>
              <div
                class="header-cell"
                style="
                  width: 300px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                药品
              </div>
              <div
                class="header-cell"
                style="
                  width: 109px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                用法
              </div>
              <div
                class="header-cell"
                style="
                  width: 140px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                频率
              </div>
              <div
                class="header-cell"
                style="
                  width: 130px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                用量/次
              </div>
              <div
                class="header-cell"
                style="
                  width: 100px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                周期
              </div>
              <div
                class="header-cell"
                style="
                  width: 100px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                总量
              </div>
              <div
                class="header-cell"
                style="flex: 1; justify-content: flex-start; padding-left: 8px"
              >
                备注
              </div>
            </div>

            <!-- 表格数据行 -->
            <div
              v-for="(row, index) in item.detailList"
              :key="row.id"
              class="table-row"
              :class="{ 'add-row': row.isNew }"
            >
              <!-- 序号 -->
              <div
                class="table-cell"
                style="width: 60px; justify-content: center"
              >
                {{ row.isNew ? '' : index + 1 }}
              </div>
              <!-- 药品名字 -->
              <div
                class="table-cell"
                style="
                  width: 300px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                <span>{{ row.drugName }}{{ row.specification }}</span>
              </div>
              <!-- 用法 -->
              <div
                class="table-cell"
                @click.stop="onUsageCode(row)"
                style="
                  width: 109px;
                  justify-content: flex-start;
                  padding-left: 8px;
                  position: relative;
                "
                v-if="prescriptionData.activeName_1 == '1'"
              >
                <div
                  style="
                    border: 1px solid #e4e7ed;
                    padding: 4px;
                    border-radius: 4px;
                    height: 32px;
                    display: inline-block;
                    min-width: 40px;
                    line-height: 22px;
                  "
                >
                  {{ row.usageCodeText }}
                </div>
                <div
                  v-if="showMedicationTabs && isShowMedicationTabs === row.uuid"
                  @click.stop
                  style="position: absolute; top: 30px; left: 0; z-index: 10"
                >
                  <MedicationTabs
                    @select="
                      (usage, usageName) => onSelect(row, usage, usageName)
                    "
                    :rxType="1"
                  />
                </div>
              </div>
              <div
                v-else
                style="
                  width: 109px;
                  justify-content: flex-start;
                  padding-left: 8px;
                  position: relative;
                "
              >
                {{ row.usageCodeText }}
              </div>
              <!-- 频率 -->
              <div
                class="table-cell"
                style="
                  width: 140px;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                <el-select
                  v-model="row.frequencyCode"
                  style="width: 100px"
                  filterable
                  class="borderless-select"
                  suffix-icon=""
                  @focus="onfrequency"
                  @change="onFrequency(row)"
                  v-if="prescriptionData.activeName_1 !== '2'"
                >
                  <el-option
                    v-for="frequency in frequency"
                    :key="frequency.frequencyCode"
                    :label="frequency.frequencyName"
                    :value="frequency.frequencyCode"
                    style="padding: 0 8px"
                  >
                    <span style="float: left">{{
                      frequency.frequencyCode
                    }}</span>
                    <span style="float: right; font-size: 13px">
                      {{ frequency.frequencyName }}
                    </span>
                  </el-option>
                </el-select>
                <div v-else style="width: 100px">
                  {{ row.frequencyCodeText }}
                </div>
              </div>
              <!-- 用量/次 -->
              <div
                class="table-cell"
                style="
                  width: 130px;
                  position: relative;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                <div style="display: flex; align-items: center; gap: 8px">
                  <el-input-number
                    v-model="row.dosage"
                    :min="0"
                    :step="0.1"
                    :max="999"
                    :controls="false"
                    class="borderless-input"
                    style="width: 50px"
                    @change="updateRow(row, index)"
                    @focus="showKeyboard(row, index, 'dosage')"
                    @click.stop
                    v-if="prescriptionData.activeName_1 !== '2'"
                  />
                  <span v-else>{{ row.dosage }}</span>
                  <span>{{ row.minPackUnitText }}</span>
                </div>

                <!-- 数字键盘 -->
                <div
                  v-if="
                    keyboardVisible &&
                    currentEditRow === row &&
                    currentEditField === 'dosage'
                  "
                  class="number-keyboard"
                  @click.stop
                >
                  <NumberDecimal @input="inputNumber" @delete="deleteNumber" />
                </div>
              </div>
              <!-- 周期 -->
              <div
                class="table-cell"
                style="
                  width: 100px;
                  position: relative;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                <div style="display: flex; align-items: center; gap: 8px">
                  <el-input-number
                    v-model="row.cycle"
                    :min="0"
                    :max="999"
                    :controls="false"
                    class="borderless-input"
                    style="width: 50px"
                    @change="updateRow(row, index)"
                    @focus="showKeyboard(row, index, 'cycle')"
                    @click.stop
                     v-if="prescriptionData.activeName_1 !== '2'"
                  />
                  <span v-else>{{ row.cycle }}</span>
                  <span>{{ row.cycleUnitText }}</span>
                </div>

                <!-- 数字键盘 -->
                <div
                  v-if="
                    keyboardVisible &&
                    currentEditRow === row &&
                    currentEditField === 'cycle'
                  "
                  class="number-keyboard"
                  @click.stop
                >
                  <NumericKeyboardInt
                    @input="inputNumber"
                    @delete="deleteNumber"
                  />
                </div>
              </div>
              <!-- 总量 -->
              <div
                class="table-cell"
                style="
                  width: 100px;
                  position: relative;
                  justify-content: flex-start;
                  padding-left: 8px;
                "
              >
                <div style="display: flex; align-items: center; gap: 4px">
                  <el-input-number
                    v-model="row.totalOutQty"
                    :min="0"
                    :max="999"
                    :controls="false"
                    class="borderless-input"
                    style="width: 50px"
                    @change="updateRow(row, index)"
                    @focus="showKeyboard(row, index, 'totalOutQty')"
                    @click.stop
                     v-if="prescriptionData.activeName_1 !== '2'"
                  />
                  <span v-else>{{  row.totalOutQty}}</span>
                  <span v-if="row.isSplit == '1'">{{
                    row.minPackUnitText
                  }}</span>
                  <span v-else>{{ row.totalOutQtyUnitText }}</span>
                </div>

                <!-- 总量数字键盘 -->
                <div
                  v-if="
                    keyboardVisible &&
                    currentEditRow === row &&
                    currentEditField === 'totalOutQty'
                  "
                  class="number-keyboard"
                  @click.stop
                >
                  <NumericKeyboardInt
                    @input="inputNumber"
                    @delete="deleteNumber"
                  />
                </div>
              </div>
              <!-- 备注 -->
              <div
                class="table-cell"
                style="flex: 1; justify-content: flex-start; padding-left: 8px"
              >
                <!-- <el-input
                  v-model="row.remark"
                  style="width: calc(100% - 30px)"
                  class="no-border-input"
                  placeholder="请输入备注"
                  @change="updateRow(row, index)"
                /> -->
                <AutocompleteMulti
                  v-model="row.remark"
                  class="borderless-select right-select"
                  placeholder=""
                  style="width: calc(100% - 30px)"
                  :trigger-on-focus="true"
                  :fetch-suggestions="querySearchAsync"
                  :selected-color="'#16ada4'"
                   v-if="prescriptionData.activeName_1 !== '2'"
                />
                <span v-else        class="multi-line">{{ row.remark }}</span>
              </div>
              <!-- 悬浮删除按钮 -->
              <div class="delete-button" @click="deleteRow(row, index)"  v-if="prescriptionData.activeName_1 == '1'">
                <img src="@/assets/manage/icon_off_hover.svg" alt="删除" />
              </div>
            </div>

            <!-- 搜索行 -->
            <div
              class="table-row search-row"
              v-if="prescriptionData.activeName_1 == '1'"
            >
              <div
                class="table-cell"
                style="width: 100%; border: none; position: relative"
              >
                <div class="table-row" style="font-size: 16px; color: #999999">
                  +
                </div>
                <el-input
                  v-model="searchText"
                  placeholder="搜索项目名称或拼音缩写"
                  class="search-input"
                  style="width: 100%"
                  clearable
                  @input="handleSearch"
                  @focus="showSearchKeyboard(indexNum)"
                  @click.stop
                />

                <!-- 搜索全键盘 -->
                <div
                  v-if="
                    searchKeyboardVisible && searchKeyboardIndex === indexNum
                  "
                  @click.stop
                >
                  <SearchKeyboard
                    :mode="keyboardMode"
                    @input="(result) => inputSearchChar(result)"
                    @delete="deleteSearchChar()"
                    @clear="clearSearch"
                    @switch="switchKeyboard"
                    v-if="searchKeyboardVisible"
                  />
                </div>

                <!-- 搜索结果下拉列表 -->
                <div
                  v-if="
                    searchResults.length > 0 &&
                    searchKeyboardVisible &&
                    searchKeyboardIndex === indexNum
                  "
                  class="search-results"
                  @click.stop
                >
                  <div class="table-header">
                    <div
                      class="header-cell"
                      style="width: 410px; text-align: left; padding-left: 16px"
                    >
                      药品
                    </div>
                    <div
                      class="header-cell"
                      style="width: 150px; text-align: left; padding-left: 16px"
                    >
                      规格
                    </div>
                    <div
                      class="header-cell"
                      style="width: 130px; text-align: left; padding-left: 16px"
                    >
                      厂家
                    </div>
                    <div
                      class="header-cell"
                      style="width: 100px; text-align: left; padding-left: 16px"
                    >
                      单价
                    </div>
                    <div
                      class="header-cell"
                      style="width: 100px; text-align: left; padding-left: 16px"
                    >
                      单位
                    </div>
                  </div>
                  <div
                    v-for="result in searchResults"
                    :key="result.id"
                    class="search-result-item"
                    @click="selectSearchResult(item.detailList, result)"
                  >
                    <div
                      class="result-name"
                      style="width: 410px; text-align: left; padding-left: 16px"
                    >
                      {{ result.drugName }}
                    </div>
                    <div
                      class="result-category"
                      style="width: 150px; text-align: left; padding-left: 16px"
                    >
                      {{ result.specification }}
                    </div>
                    <div
                      class="result-spec"
                      style="width: 130px; text-align: left; padding-left: 16px"
                    >
                      {{ result.mfrName }}
                    </div>
                    <div
                      class="result-price"
                      style="width: 100px; text-align: left; padding-left: 16px"
                    >
                      ¥ {{ (result.price / 100).toFixed(2) }}
                    </div>
                    <div
                      class="result-spec"
                      style="width: 100px; text-align: left; padding-left: 16px"
                    >
                      {{ result.packUnitText }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="table-cell" style="width: 100px"></div>
              <div class="table-cell" style="width: 120px"></div>
              <div class="table-cell" style="width: 180px"></div>
              <div class="table-cell" style="width: 100px"></div>
              <div class="table-cell" style="flex: 1"></div>
            </div>
          </template>
        </div>
      </div>
      <div v-if="item.rxType == '2'" style="margin-top: 10px">
        <div>
          <!-- 输液 -->
          <transfusion
            :visitStatus="prescriptionData.activeName_1"
            :group="item"
            @searchKeyboard="onSearchKeyboard(item.uuid)"
            :displayNowUUid2="displayNowUUid"
            :recomScene="recomScene"
            ref="transfusionRef"
            @addNewRow="(result) => addNewRow(result, indexNum)"
            @removeRow="(result) => removeRow(result, indexNum)"
          />
        </div>
      </div>
      <!-- 中药处方二 -->
      <div
        class="custom-table"
        v-if="item.rxType == '3'"
        style="margin-top: 10px"
      >
        <medicinalHerb
          :medicinalHerbData="item"
          :visitStatus="prescriptionData.activeName_1"
          ref="medicinalHerbRef"
           :recomScene="recomScene"
          @removeRow="(result) => removeRow(result, indexNum)"
        ></medicinalHerb>
      </div>

      <!-- 外治处方三 -->
      <div v-if="item.rxType == '4'" style="margin-top: 10px">
        <ExternalTreatment
          :externalTreatment="item"
           :recomScene="recomScene"
          :visitStatus="prescriptionData.activeName_1"
          ref="externalTreatmentRef"
          @removeRow="(result) => removeRow(result, indexNum)"
        />
      </div>
    </template>

    <div style="height: 350px">
      <!-- 底部留白 -->
    </div>
    <!-- 检验 -->
    <div>
      <el-dialog
        v-model="dialogVisible"
        class="custom-transition-dialog"
        width="50%"
      >
        <Examine
          :tableData="displayTableData"
          :frequencyOptions="frequency"
          @updateRow="updateRow"
          @close="onCloseExamine"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  addTemplatePrescription,
  updateTemplatePrescription,
} from '@/api/formwork';
import { CaretBottom } from '@element-plus/icons-vue';
import { getDrugRxList } from '@/api/formwork';
import ExternalTreatment from './ExternalTreatment.vue';
import medicinalHerb from './medicinalHerb.vue';
import transfusion from './transfusion.vue';
import TagInput from './TagInput.vue';
import AutocompleteMulti from '@/components/AutocompleteMulti.vue';
import stores from '@/store';
import Examine from './examine.vue';
import { v4 as uuidv4 } from 'uuid';
import { calculateTotalDose } from '@/utils/rxUtil';
const useBaseData = stores.useBaseDataStore();
const frequency = ref(useBaseData.getDictsSelect('FREQUENCY'));
const recomScene = ref<string>('');
const formData = ref<any>({
  fieldList: [],
  templateName: '',
  templateType: '1',
  recomScene: '',
  groupId: '',
});
// 定义数据类型
interface InspectionItem {
  id: number;
  name: string;
  category: '检验' | '检查';
  frequency: string;
  period: number;
  totalCount: number;
  remark: string;
  isNew?: boolean;
}

// 响应式数据
const activeType = ref<any>('1');
const searchKeyword = ref('');
const searchLoading = ref(false);
const dialogVisible = ref(false);
const searchKeyboardIndex = ref(-1);
// 用法弹窗相关
const showMedicationTabs = ref<boolean>(false);
const currentUsageRow = ref<any | null>(null);
const searchOptions = ref<
  { label: string; value: string; category: '检验' | '检查' }[]
>([]);

// 搜索功能
const searchText = ref('');
const searchKeyboardVisible = ref(false);
const keyboardMode = ref<'english' | 'chinese'>('english');
const searchResults = ref<Array<any>>([]);
const displayNowUUid = ref('');
// 数字键盘相关
const keyboardVisible = ref(false);
const currentEditRow = ref<any | null>(null);
const currentEditField = ref<any>(null);
const detailList = ref<any[]>([]); //中西成药处方一 模板数据
const groupList = ref<any[]>([]); //输注处方四 模板数据
// 这些组件在 v-for 中使用了相同的 template ref 名称，Vue 会将它们收集为“数组模板引用”
const prescriptionRef = ref<InstanceType<any>[]>([]); // 处方（数组）
const transfusionRef = ref<InstanceType<any>[]>([]); // 输液（数组）
const medicinalHerbRef = ref<InstanceType<any>[]>([]); // 中药（数组）
const externalTreatmentRef = ref<InstanceType<any>[]>([]); // 外治处方（数组）
const isShowMedicationTabs = ref<any>(null);
// 用法弹框事件
const onSelect = (row: any, usage: any, usageName: any) => {
  //console.log('usage', usage);
  //console.log('currentUsageRow', currentUsageRow.value);
  row.usageCode = usage.value[0];
  row.usageCodeText = usageName;
  // // 判断是否已存在，存在则更新，不存在则添加
  // const idx = detailList.value.findIndex(
  //   (item) => item.drugId === currentUsageRow.value.drugId
  // );
  // if (idx > -1) {
  //   detailList.value[idx] = {
  //     ...detailList.value[idx],
  //     ...currentUsageRow.value,
  //   };
  // } else {
  //   detailList.value.push({ ...currentUsageRow.value });
  // }
  // prescriptionTypeList.value.forEach((item: any) => {
  //   if (item.rxType == '1') {
  //     item.detailList = detailList.value;
  //   }
  // });
  showMedicationTabs.value = false;
};
const isInitialLoad = ref(true);

// 表格数据
const tableData = ref<any[]>([
  {
    id: 1,
    name: '肝功能',
    category: '检查',
    frequency: '1天1次',
    period: 1,
    totalCount: 1,
    remark: '悬停可删除',
  },
  {
    id: 2,
    name: '血常规',
    category: '检验',
    frequency: '3天1次',
    period: 3,
    totalCount: 1,
    remark: '',
  },
  {
    id: 3,
    name: '尿常规',
    category: '检验',
    frequency: '1周1次',
    period: 1,
    totalCount: 1,
    remark: '',
  },
  {
    id: 3,
    name: '尿常规',
    category: '检验',
    frequency: '1周1次',
    period: 1,
    totalCount: 1,
    remark: '',
  },
  {
    id: 4,
    name: 'CT检查',
    category: '检查',
    frequency: '1月1次',
    period: 1,
    totalCount: 1,
    remark: '',
  },
]);
const prescriptionTypeList = ref<any[]>([]);
const prescriptionData = defineProps<{
  selectedGroupId: any;
  templateMedicalDetail: any;
  dataType: string;
  activeName_1: string;
}>();
watch(
  () => [
    prescriptionData.dataType,
    prescriptionData.templateMedicalDetail?.templateId,
  ],
  () => {
    const dataType = prescriptionData?.dataType;
    const detail = prescriptionData?.templateMedicalDetail || {};
    isInitialLoad.value = true;

    if (dataType === '1') {
      // 新建：重置本地状态
      prescriptionTypeList.value = [];
      recomScene.value = '';
      formData.value.templateName = '';
      formData.value.recomScene = '';
      formData.value.templateId = '';
      return;
    }

    // 编辑：根据传入详情初始化
    formData.value.templateName = detail?.templateName || '';
    formData.value.recomScene = detail?.recomScene || '';
    formData.value.templateId = detail?.templateId || '';
    recomScene.value = detail?.recomScene || '';

    // 防御性处理：rxList 可能为 undefined/null
    const rawList = Array.isArray(detail?.rxList) ? detail.rxList : [];
    prescriptionTypeList.value = rawList.map((item: any) => {
      const cloned = { ...item };
      const details = Array.isArray(cloned.detailList) ? cloned.detailList : [];
      cloned.detailList = details.map((detail: any) => ({
        ...detail,
        uuid: uuidv4(),
        specification:
          detail.drugCategory == 3
            ? `${detail.minPackQty}${detail.minPackUnitText}/${detail.packUnitText}`
            : `${detail.drugDosage}${detail.drugDosageUnitText}*${detail.minPackQty}${detail.minPackUnitText}/${detail.packUnitText}`,
      }));
      cloned.uuid = uuidv4();

      return cloned;
    });
    //console.log(prescriptionTypeList.value);
    if (detail?.rxList && detail?.rxList.length == 0) {
      setActiveType('1');
    }
  },
  { immediate: true }
);
const onSearchKeyboard = (value: string) => {
  displayNowUUid.value = value;
};
const onFrequency = (row: any) => {
  const selectedFrequency = frequency.value?.find(
    (freq: { frequencyCode: any }) => freq.frequencyCode === row.frequencyCode
  );
  showMedicationTabs.value = false;
  keyboardVisible.value = false;
  searchKeyboardVisible.value = false;
  if (selectedFrequency) {
    row.cycleUnit = selectedFrequency.cycleUnit;
    row.cycleUnitText = useBaseData.getEnumData(
      selectedFrequency.cycleUnit,
      'cycleUnitEnum'
    );
  }
};
// 计算属性：过滤后的表格数据
const filteredTableData = computed(() => {
  let filtered = tableData.value;

  // 根据类型过滤
  if (activeType.value === 'inspection') {
    filtered = filtered.filter((item) => item.category === '检验');
  } else {
    filtered = filtered.filter((item) => item.category === '检查');
  }

  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(
      (item) =>
        item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        item.remark.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }

  return filtered;
});
// 删除行方法
const deleteRow = (row: any, index: number) => {
  //console.log(row);
  const group = prescriptionTypeList.value.find(
    (g: any) =>
      g.detailList && g.detailList.some((item: any) => item.uuid === row.uuid)
  );
  if (group) {
    group.detailList = group.detailList.filter(
      (item: { uuid: any }) => item.uuid !== row.uuid
    );
  }
  // ElMessage.success('项目删除成功');
};
// 显示的表格数据（包含新增行）
const displayTableData = computed(() => {
  const filtered = filteredTableData.value;

  return [...filtered];
});

// 方法
const setActiveType = (type: string) => {
  activeType.value = type;
  // 构造不同类型的处方对象
  // 统计同类型数量
  const sameTypeCount = prescriptionTypeList.value.filter(
    (i) => i.rxType === type
  ).length;
  let newRx: any = {
    rxType: type,
    rxName: '',
    payStatus: null,
    payTime: null,
    storageId: null,
    totalAmount: null,
    uuid: uuidv4(),
  };
  switch (type) {
    case '1':
      newRx.rxName = `中西成药处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.detailList = [];
      break;
    case '2':
      newRx.rxName = `输注处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.groupList = [
        {
          groupName: '第一组',
          usageCode: 'JMDZ',
          usageCodeText: '静脉滴注',
          frequencyCode: 'qd',
          frequencyCodeText: '1天1次',
          cycle: 1,
          cycleUnit: 'day',
          cycleUnitText: '天',
          ivDripRate: '50',
          subtotal: 1000,
          uuid: uuidv4(),
        },
      ];
      break;
    case '3':
      newRx.rxName = `中药处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.tcmInfo = {
        frequencyCode: 'bid',
        frequencyCodeText: '1天2次',
        dailyDosage: '1',
        cycle: 7,
        cycleUnit: 'day',
        cycleUnitText: '天',
        usageCode: 'JFU',
        usageCodeText: '煎服',
        singleDosage: '200',
        remark: '',
        totalDoses: 0,
        subtotal: 0,
        detailList: [],
        uuid: uuidv4(), // 唯一标识
      };
      break;
      break;
    case '4':
      newRx.rxName = `外治处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.extInfo = {
        projectId: '',
        projectName: '',
        projectCategory: '',
        price: 0,
        projectType: '',
        frequencyCode: 'qd',
        frequencyCodeText: '1天1次',
        cycle: 1,
        cycleUnit: 'day',
        cycleUnitText: '天',
        remark: '',
        totalOutQty: '',
        totalOutQtyUnit: '',
        totalOutQtyUnitText: '',
        subtotal: '',
        detailList: [],
        uuid: uuidv4(), // 唯一标识
      };
      newRx.detailList = [];
      break;
  }
  prescriptionTypeList.value.push(newRx);
};

const addNewItem = () => {
  ElMessage.info('添加新项目功能待开发');
  // 这里可以打开添加对话框
};

// 搜索方法
const handleSearch = async (value: string) => {
  //console.log('搜索内容:', value);

  // 模拟搜索结果数据

  const result = await getDrugRxList({
    drugName: value,
    drugCategory: '1',
    recoms: recomScene.value,
  });
  searchResults.value =
    result?.data.map((item: any) => ({
      ...item,
      drugCategoryName: useBaseData.getEnumData(
        item.drugCategory,
        'drugCategoryEnum'
      ),
      specification:
        item.drugCategory == 3
          ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
          : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
      usageCode: item?.usageList?.[0]?.usageCode || '',
      usageCodeText: '',
      cycle: 1,
      totalOutQty: 1,
      frequencyCode: 'qd',
      cycleUnit: 'day',
      cycleUnitText: '天',
      dosage: '1',
      dosageUnit: '',
      mfrName: useBaseData.getMfrName(item.mfrId),
      dosageUnitText: item.drugDosageUnitText,
      totalOutQtyUnit: '',
      totalOutQtyUnitText: item.packUnitText,
      isSplit: item.isSplit,
      minPackUnitText: item.minPackUnitText,
    })) || [];
};
const removeRow_1 = (group: any, index: any) => {
  prescriptionTypeList.value.splice(index, 1);
};
// 数字改成中文
const toChineseNumber = (num: number) => {
  const cnNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const cnUnits = ['', '十', '百', '千', '万'];
  if (num < 10) return cnNums[num];
  if (num < 20) return '十' + (num === 10 ? '' : cnNums[num % 10]);
  if (num < 100) {
    const ten = Math.floor(num / 10);
    const unit = num % 10;
    return cnNums[ten] + '十' + (unit === 0 ? '' : cnNums[unit]);
  }
  // 这里只处理到99，更多位数可扩展
  return num;
};
// 添加处方
const addNewRow = (group?: any, index?: any) => {
  const num = index + 1;
  const data = {
    groupList: group,
    rxType: '',
    uuid: uuidv4(), // 唯一标识
    rxName: '输注处方' + toChineseNumber(num),
  };
  prescriptionTypeList.value = prescriptionTypeList.value.concat(data);
  ElMessage.success('添加成功');
};
// 删除处方
const removeRow = (group?: any, index?: any) => {
  prescriptionTypeList.value.splice(index, 1);
  ElMessage.success('处方已删除');
};

// 搜索键盘相关方法
const showSearchKeyboard = (index: number) => {
  searchKeyboardIndex.value = index;
  searchKeyboardVisible.value = true;
  showMedicationTabs.value = false;
  keyboardVisible.value = false;
  handleSearch(searchText.value);
  // 添加键盘事件监听器
  document.addEventListener('keydown', handleKeyboardShortcut);
};

const hideSearchKeyboard = (event?: Event) => {
  // 如果点击的是键盘内部或搜索结果，不隐藏
  if (event && event.target) {
    const target = event.target as Element;
    if (
      target.closest('.search-keyboard') ||
      target.closest('.search-results') ||
      target.closest('.search-input')
    ) {
      return;
    }
  }

  searchKeyboardVisible.value = false;
  // 移除键盘事件监听器
  document.removeEventListener('keydown', handleKeyboardShortcut);
};

// 处理键盘快捷键
const handleKeyboardShortcut = (event: KeyboardEvent) => {
  // Ctrl + Shift + T 切换键盘模式
  if (event.ctrlKey && event.shiftKey && event.key === 'T') {
    event.preventDefault();
    switchKeyboard();
  }
  // Esc 键隐藏键盘
  else if (event.key === 'Escape') {
    event.preventDefault();
    hideSearchKeyboard();
  }
};
const onfrequency = () => {
  showMedicationTabs.value = false;
  keyboardVisible.value = false;
  searchKeyboardVisible.value = false;
};
const inputSearchChar = (char: string) => {
  searchText.value += char;
  handleSearch(searchText.value);
};

const deleteSearchChar = () => {
  if (searchText.value.length > 0) {
    searchText.value = searchText.value.slice(0, -1);
    handleSearch(searchText.value);
  }
};

const clearSearch = () => {
  searchText.value = '';
  searchResults.value = [];
};

const switchKeyboard = () => {
  if (keyboardMode.value === 'english') {
    keyboardMode.value = 'chinese';
  } else if (keyboardMode.value === 'chinese') {
    keyboardMode.value = 'english';
  }
};

// const selectSearchResult = (result: any) => {
//   // 选择搜索结果
//   //console.log('选择了:', result);
//   ElMessage.success(`已选择: ${result.name}`);
//   searchKeyboardVisible.value = false;
//   searchResults.value = [];
//   searchText.value = '';
// };
const selectSearchResult = (_detailList: any, result: any) => {
  result.uuid = uuidv4(); // 为每一行添加唯一标识符
  result.usageCodeText = '口服'; // 标记为非新行
  result.usageCode = 'KF'; // 默认用法代码
  result.frequencyCode = 'tid'; // 默认频率代码
  result.cycleUnit = 'day';
  result.cycleUnitText = '天';
  result.dosage = null;
  result.cycle = null;
  result.totalOutQty = null;
  result.remark = result.instrs;
  //   cycle: 1,
  // totalOutQty: 1,
  // frequencyCode: 'qd',
  // cycleUnit: 'day',
  // cycleUnitText: '天',
  _detailList.push(result);
  searchKeyboardVisible.value = false;
  searchResults.value = [];
  searchText.value = '';
};
const querySearchAsync = (queryString: string, cb: any) => {
  const data1 = useBaseData.getDictsSelect('REMARK') || [];
  // 仅保留 rxType 为 5 的项（兼容数字/字符串）
  const filtered = (Array.isArray(data1) ? data1 : []).filter(
    (item: any) => item?.rxType === 5 || item?.rxType === '1'
  );
  const results = filtered.map((item: any) => ({
    value: item.remarkText,
    ...item,
  }));
  cb(results);
};
// 备注支持多选：选择后以逗号分隔叠加，若正在输入部分（最后一个片段）则替换为所选项
const onRemarkSelect = (row: any, suggestion: any) => {
  const text: string = suggestion?.value ?? suggestion?.remarkText ?? '';
  if (!text) return;

  const current = (row.remark || '').toString();
  if (!current) {
    row.remark = text;
    return;
  }

  // 拆分为片段并清理空白
  const parts = current
    .split(',')
    .map((s: string) => s.trim())
    .filter((s: string) => s.length > 0);

  // 如果末尾有逗号，说明用户准备添加新项 => 直接追加；否则替换最后一个片段（处理半输入选择）
  const endsWithComma = /,\s*$/.test(current);
  if (endsWithComma || parts.length === 0) {
    parts.push(text);
  } else {
    parts[parts.length - 1] = text;
  }

  // 去重但保留顺序（避免重复项）
  const uniqueParts = Array.from(new Set(parts));
  row.remark = uniqueParts.join(', ');
};
const updateRow = (row: any, index: number) => {
  // 当编辑现有行时，自动保存更改
  if (!row.isNew) {
    //console.log('更新行数据:', row);
    // ElMessage.success('数据已更新');
  }
};

// ================= 使用 rxUtil.calculateTotalDose 自动计算 totalOutQty START =================
// 监听 prescriptionTypeList 内 detailList 行的 frequencyCode / dosage / cycle 改变
// 仅针对 rxType === '1' (中西成药处方) 行进行计算；如需扩展其他类型可追加条件

// 从频率名称中兜底解析每天次数，例如："1天3次" / "每日2次" / "QD"(可按需要扩展)
function parseTimesPerDayFromName(name: string): number | null {
  if (!name) return null;
  // // 1天3次 / 2天1次 （按每天次数换算 = (次数 / 天数)）
  // let m = name.match(/(\d+)天(\d+)次/);
  // if (m) {
  //   const days = parseInt(m[1]);
  //   const times = parseInt(m[2]);
  //   if (days > 0) return Math.ceil(times / days); // 向上取整保障最小次数
  // }
  // // 每日X次 / 1天X次
  // m = name.match(/(每日|1天)(\d+)次/);
  // if (m) {
  //   return parseInt(m[2]);
  // }
  // // 常见英文缩写可按需要补齐：QD(1次/日) BID(2) TID(3) QID(4)
  // const upper = name.toUpperCase();
  // if (upper === 'QD') return 1;
  // if (upper === 'BID') return 2;
  // if (upper === 'TID') return 3;
  // if (upper === 'QID') return 4;
  return null;
}

function recalcTotalOutQty() {
  prescriptionTypeList.value.forEach((group: any) => {
    if (!group || group.rxType !== '1' || !Array.isArray(group.detailList))
      return;
    group.detailList.forEach((row: any) => {
      const dosageNum = Number(row.dosage);
      const cycleNum = Number(row.cycle);
      if (
        !row.frequencyCode ||
        isNaN(dosageNum) ||
        dosageNum <= 0 ||
        isNaN(cycleNum) ||
        cycleNum <= 0
      )
        return;
      const freqItem = frequency.value?.find(
        (f: any) => f.frequencyCode === row.frequencyCode
      );
      // 频率对象可能有 frequencyTimes 字段
      let timesPerDay = Number(freqItem?.frequencyTimes);
      //console.log(dosageNum, timesPerDay, cycleNum, row.isSplit);

      const newTotal = calculateTotalDose(
        dosageNum,
        timesPerDay,
        cycleNum,
        row.isMinSplit,
        row.isSplit,
        row.minPackQty
      );
      row.totalOutQty = newTotal;
    });
  });
}
// 从频率代码获取每天次数
// function getTimesPerDayFromCode(code: string): number {
//   if (!code) return 0;
//   const item = props.frequencyOptions?.find(
//     (f: any) => f.frequencyCode === code
//   );
//   return Number(item?.frequencyTimes) || 0;
// }
function recalcRowTotalOutQty1(row: any) {
  const dosage = Number(row.dosage);
  const cycle = Number(row.cycle);
  // const times = getTimesPerDayFromCode(row.frequencyCode);
  const freqItem = frequency.value?.find(
    (f: any) => f.frequencyCode === row.frequencyCode
  );
  // 频率对象可能有 frequencyTimes 字段
  let timesPerDay = Number(freqItem?.frequencyTimes);
  if (!timesPerDay || !dosage || dosage <= 0 || !cycle || cycle <= 0) return;
  row.totalOutQty = calculateTotalDose(
    dosage,
    timesPerDay,
    cycle,
    row.isMinSplit,
    row?.isSplit,
    row.minPackQty
  );
}
// 深度差异比较函数
function getDeepChanges(newObj: any[], oldObj: any[], path = '') {
  if (!oldObj) return [{ path, newValue: newObj }];

  if (Array.isArray(newObj)) {
    const changes: any[] = [];
    newObj.forEach((item, index) => {
      changes.push(...getDeepChanges(item, oldObj[index], `${path}[${index}]`));
    });
    return changes;
  }

  return newObj !== oldObj
    ? [{ path, oldValue: oldObj, newValue: newObj }]
    : [];
}
function extractDifferences(changeItems: any[]) {
  // 深度比较两个值是否相等
  function isDeepEqual(
    a: { [x: string]: any } | null,
    b: { [x: string]: any } | null
  ) {
    if (a === b) return true;
    if (
      typeof a !== 'object' ||
      a === null ||
      typeof b !== 'object' ||
      b === null
    )
      return false;

    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;

    for (const key of keysA) {
      if (!keysB.includes(key)) return false;
      if (!isDeepEqual(a[key], b[key])) return false;
    }
    return true;
  }

  return changeItems
    .map((item) => {
      const { path, oldValue, newValue } = item;
      const uuid = newValue?.uuid || oldValue?.uuid; // 获取UUID

      const changedFields: any = {};

      // 收集所有key，包括oldValue和newValue中的
      const allKeys = new Set([
        ...Object.keys(oldValue || {}),
        ...Object.keys(newValue || {}),
      ]);

      // 比较每个字段
      for (const key of allKeys) {
        const oldVal = oldValue?.[key];
        const newVal = newValue?.[key];
        // 只有当值确实不同时才记录
        if (!isDeepEqual(oldVal, newVal)) {
          changedFields[key] = {
            old: oldVal,
            new: newVal,
            uuid: uuid,
          };
        }
      }

      // 只返回有实际变化的项
      return Object.keys(changedFields).length > 0
        ? { path, changes: changedFields, uuid }
        : null;
    })
    .filter(Boolean); // 过滤掉没有实际变化的项
}

// 深度监听需要的字段（以最小依赖集合触发）
watch(
  () =>
    prescriptionTypeList.value.map((g: any) =>
      Array.isArray(g.detailList)
        ? g.detailList.map((r: any) => ({
            uuid: r.uuid,
            f: r.frequencyCode,
            d: r.dosage,
            c: r.cycle,
            code: r.usageCode,
            tq: r.totalOutQty,
          }))
        : []
    ),
  (newSnap, oldSnap) => {
    console.log(prescriptionTypeList.value);
    if (isInitialLoad.value) {
      isInitialLoad.value = false;
      return;
    }
    const diffs = extractDifferences(getDeepChanges(newSnap, oldSnap));
    //console.log('实际变化的字段:', diffs);
    const changedUUIDs = diffs.map((diff: any) => diff.uuid).filter(Boolean);
    // recalcTotalOutQty();
    prescriptionTypeList.value.forEach((group: any) => {
      if (group || group.rxType == '1' || Array.isArray(group.detailList)) {
        group.detailList.forEach((row: any) => {
          if (
            changedUUIDs.includes(row.uuid) &&
            currentEditField.value != 'totalOutQty'
          ) {
            recalcRowTotalOutQty1(row);
          }
        });
      }
    });
  },
  { deep: true }
);
// 数字键盘相关方法
const showKeyboard = (
  row: any,
  index: number,
  field: 'dosage' | 'totalOutQty' | 'cycle'
) => {
  currentEditRow.value = row;
  currentEditField.value = field;
  keyboardVisible.value = true;
  showMedicationTabs.value = false;
  searchKeyboardVisible.value = false;
};

const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.number-keyboard')) {
      return;
    }
  }

  keyboardVisible.value = false;
  currentEditRow.value = null;
  currentEditField.value = null;
};

const inputNumber = (num: string, type?: string) => {
  console.log('键盘输入值:', num, '类型:', type);
  if (type) {
    // 直接设置数值（来自NumberDecimal组件）
    currentEditRow.value[currentEditField.value] = Number(num);
  }

  // 有效性检查
  if (!currentEditRow.value || !currentEditField.value) {
    return;
  }

  // 获取当前值和字段配置
  const field = currentEditField.value;
  const currentValue = currentEditRow.value[field];
  const isDecimalField = ['dosage', 'splitPrice'].includes(field); // 假设这些字段允许小数

  // 处理小数点输入
  if (num === '.') {
    // if (!isDecimalField) {
    //   //console.log('小数点输入被拒绝，该字段不支持小数');
    //   return;
    // }

    // 如果当前值已经是小数或包含小数点，不再添加
    const currentStr = currentValue?.toString() || '';
    if (currentStr.includes('.')) {
      return;
    }

    // 添加小数点
    currentEditRow.value[field] = currentStr + '.';
    return;
  }

  // 处理数字输入
  let newValue: number | string;

  // 初始化或处理现有值
  if (currentValue === undefined || currentValue === null) {
    newValue =
      isDecimalField && currentEditRow.value[field]?.toString().includes('.')
        ? '0.' + num
        : num;
  } else {
    const currentStr = currentValue.toString();

    if (isDecimalField && currentStr.includes('.')) {
      // 小数部分拼接
      const [integer, decimal] = currentStr.split('.');
      newValue = `${integer}.${decimal}${num}`;
    } else {
      // 整数部分拼接
      newValue = currentStr === '0' ? num : currentStr + num;
    }
  }

  // 转换为数字并验证范围
  const numericValue = Number(newValue);
  const maxValue = 999; // 根据字段获取最大值

  if (numericValue <= maxValue) {
    currentEditRow.value[field] = isDecimalField
      ? numericValue
      : Math.floor(numericValue);
  } else {
  }
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) {
    //console.log('deleteNumber: currentEditRow or currentEditField is null');
    return;
  }

  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    //console.log('deleteNumber: current value is undefined/null');
    return;
  }

  // const currentValueStr = currentValue.toString();
  // const newValue = parseInt(currentValueStr.slice(0, -1)) || 1;
  // currentEditRow.value[currentEditField.value] = newValue;
  const currentValueStr = currentValue.toString();
  const newValue = currentValueStr.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
};

const confirmAdd = (row: any, index: number) => {
  if (!row.name.trim()) {
    ElMessage.warning('请选择项目');
    return;
  }

  // 根据选择的项目添加新项目
  const selectedOption = searchOptions.value.find(
    (opt) => opt.value === row.name
  );
  const newItem: any = {
    id: Date.now(),
    name: selectedOption?.label || row.name,
    category:
      selectedOption?.category ||
      (activeType.value === 'inspection' ? '检验' : '检查'),
    frequency: row.frequency,
    period: row.period,
    totalCount: row.totalCount,
    remark: row.remark || '新添加项目',
  };

  tableData.value.push(newItem);
  ElMessage.success('项目添加成功');

  // 重置搜索选项
  searchOptions.value = [];
};
const addTag = (tags: string[]) => {
  formData.value.recomScene = tags.join(',');
  recomScene.value = tags.join(',');
};
// 格式化数据
const dataProcess = () => {
  // 2) 查验项目最小化
  const safeMap = (arr: any, fn: (x: any) => any) =>
    Array.isArray(arr) ? arr.map(fn) : [];
  const findByUuid = <T>(
    list: T[] | undefined,
    pick: (x: T) => any,
    uuid: any
  ) => {
    if (!Array.isArray(list)) return undefined;
    return list.find((inst: any) => pick(inst)?.uuid === uuid);
  };
  const rxList = safeMap(prescriptionTypeList.value, (rx: any) => {
    const rxType = String(rx?.rxType || '');
    const uuid = rx?.uuid;
    let src: any = rx; // 兜底：使用 medicalList 中的对象

    if (rxType === '1') {
      const inst = findByUuid(
        prescriptionRef.value,
        (c: any) => c?.displayNow,
        uuid
      );
      if (inst?.displayNow) src = inst.displayNow;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxType: '1',
        detailList: safeMap(src.detailList, (d: any) => ({
          drugId: d.drugId,
          usageCode: d.usageCode,
          frequencyCode: d.frequencyCode,
          dosage: d.dosage,
          cycle: d.cycle,
          remark: d.remark,
          totalOutQty: d.totalOutQty,
        })),
      };
    }
    if (rxType === '2') {
      const inst = findByUuid(
        transfusionRef.value,
        (c: any) => c?.transfusionTableData,
        uuid
      );
      console.log(inst);

      if (inst?.transfusionTableData) src = inst.transfusionTableData;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxType: '2',
        groupList: safeMap(src.groupList, (g: any) => ({
          groupName: g.groupName,
          usageCode: g.usageCode,
          frequencyCode: g.frequencyCode,
          cycle: g.cycle,
          ivDripRate: g.ivDripRate,
          detailList: safeMap(g.detailList, (d: any) => ({
            drugId: d.drugId,
            dosage: d.dosage,
            skinTest: d.skinTest,
            remark: d.remark,
            totalOutQty: d.totalOutQty,
          })),
        })),
      };
    }
    if (rxType === '3') {
      const inst = findByUuid(
        medicinalHerbRef.value,
        (c: any) => c?.externalTreatment,
        uuid
      );
      if (inst?.externalTreatment) src = inst.externalTreatment;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxType: '3',
        tcmInfo: {
          usageCode: src.tcmInfo?.usageCode,
          frequencyCode: src.tcmInfo?.frequencyCode,
          cycle: src.tcmInfo?.cycle,
          dailyDosage: src.tcmInfo?.dailyDosage,
          singleDosage: src.tcmInfo?.singleDosage,
          remark: src.tcmInfo?.remark,
          detailList: safeMap(src.tcmInfo?.detailList, (d: any) => ({
            drugId: d.drugId,
            dosage: d.dosage,
            decotionMethod: d.decotionMethod,
          })),
        },
      };
    }
    if (rxType === '4') {
      const inst = findByUuid(
        externalTreatmentRef.value,
        (c: any) => c?.externalTreatment,
        uuid
      );
      if (inst?.externalTreatment) src = inst.externalTreatment;
      return {
        rxName: src.rxName,
        rxType: '4',
        extInfo: {
          projectId: src.extInfo?.projectId,
          frequencyCode: src.extInfo?.frequencyCode,
          cycle: src.extInfo?.cycle,
          remark: src.extInfo?.remark,
          detailList: safeMap(src.extInfo?.detailList, (d: any) => ({
            acupointCode: d.acupointCode,
            sideType: d.sideType,
          })),
        },
      };
    }
    return null;
  }).filter(Boolean);
  //console.log(rxList);
  return rxList;
};
// 保存
const addDepApi = async () => {
  if (prescriptionData.dataType == '1') {
    if (formData.value.templateName.trim() === '') {
      ElMessage.warning('模板名称不能为空');
      return;
    }
    if (formData.value.recomScene.trim() === '') {
      ElMessage.warning('适用场景不能为空');
      return;
    }
    if (prescriptionTypeList.value.length === 0) {
      ElMessage.warning('请添加至少一个项目');
      return;
    }
    formData.value.fieldList = dataProcess();
    const data = await addTemplatePrescription(formData.value);
    if (data.code == '200') {
      ElMessage.success('保存成功');
      // 清空表单
    } else {
      //ElMessage.error(data.msg || '保存失败');
    }
  } else {
    if (formData.value.templateName.trim() === '') {
      ElMessage.warning('模板名称不能为空');
      return;
    }
    formData.value.rxList = dataProcess();
    const data = await updateTemplatePrescription(formData.value);
    if (data.code == '200') {
      ElMessage.success('保存成功');
      // 清空表单
    } else {
      //ElMessage.error(data.msg || '保存失败');
    }
  }
};
const onUsageCode = (row: any) => {
  isShowMedicationTabs.value = row.uuid;
  if (currentUsageRow.value === row && showMedicationTabs.value) {
    // 再次点击同一行则关闭
    showMedicationTabs.value = false;
    currentUsageRow.value = null;
  } else {
    showMedicationTabs.value = true;
    currentUsageRow.value = row;
  }
  searchKeyboardVisible.value = false;
  keyboardVisible.value = false;
};

// 点击其他地方关闭 MedicationTabs
const handleGlobalClick = (event: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.medication-tabs')) {
      return;
    }
  }
  showMedicationTabs.value = false;
  currentUsageRow.value = null;
};
const onCloseExamine = () => {
  dialogVisible.value = false;
  activeType.value = '';
};
// 统一全局点击处理函数，避免 onMounted/onUnmounted 内部重复定义导致无法移除
const globalClickHandler = (event: Event) => {
  hideKeyboard(event);
  hideSearchKeyboard(event);
  handleGlobalClick(event);
};
onMounted(() => {
  document.addEventListener('mousedown', globalClickHandler);
});
onUnmounted(() => {
  document.removeEventListener('mousedown', globalClickHandler);
});
</script>
<style lang="scss" scoped>
::v-deep(.el-select-dropdown__item) {
  padding: 0 16px 0 16px !important;
}
.multi-line {
  display: -webkit-box; /* 使用flexbox布局 */
  -webkit-line-clamp: 2; /* 限制显示行数 */
  -webkit-box-orient: vertical; /* 垂直排列 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
}
.inspection-container-1 {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  // box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 136px);
  overflow: auto;
  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 16px 0px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .action-buttons {
      display: flex;
      .el-button.active {
        background-color: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }

  .search-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 6px;
  }

  // 自定义表格样式
  .custom-table {
    width: 100%;
    border-radius: 6px;
    overflow: visible;
    min-height: 100px;
    border-radius: 12px;
    position: relative; // 添加相对定位
    .table-header {
      display: flex;
      padding: 0;
      background-color: #f8f8f8;
      border-bottom: 1px solid #e4e7ed;
      .header-cell {
        padding: 12px 8px;
        text-align: left;
        font-weight: 600;
        color: #909399;
        font-size: 14px;
        border-right: none;
        display: flex;
        align-items: center;
        justify-content: flex-start;
      }
    }

    .table-row {
      display: flex;
      border-bottom: 1px solid #e4e7ed;
      position: relative;
      align-items: center;
      &:hover {
        .delete-button {
          opacity: 1;
          visibility: visible;
        }
      }
      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f5f7fa;
      }

      &.add-row {
        background-color: #fafafa;
      }

      .table-cell {
        padding: 12px 8px;
        text-align: left;
        display: flex;
        align-items: center;
        border-right: none;
        height: 50px;
        position: relative;
        justify-content: flex-start;

        &:last-child {
          justify-content: flex-start;
          padding-left: 12px;
        }

        // 特殊处理包含键盘的单元格
        &:has(.number-keyboard) {
          overflow: visible;
          z-index: 1;
        }
      }
    }
  }

  // 无边框输入框样式
  :deep(.borderless-select) {
    // 修改后缀图标颜色
    .el-icon {
      color: #000000; // 设置图标颜色为蓝色，你可以改成任何颜色
    }
  }

  :deep(.borderless-input) {
    .el-input__wrapper {
      border: 1px solid #dcdfe6;
      box-shadow: none;
    }
  }
  :deep(.no-border-input) {
    .el-input__wrapper {
      box-shadow: none;
    }
  }

  // 数字键盘样式
  .number-keyboard {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 9999 !important;
    background: white;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    // padding: 8px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25); // 增强阴影效果
    margin-top: 4px;
    transform: translateZ(0); // 硬件加速，确保显示在最顶层

    .keyboard-row {
      display: flex;
      gap: 4px;
      margin-bottom: 4px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .key-btn {
      width: 50px;
      height: 40px;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      background: #f8f9fa;
      color: #333;
      font-size: 16px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: #e9ecef;
        border-color: #409eff;
      }

      &:active {
        background: #dee2e6;
        transform: scale(0.95);
      }

      &.delete-btn {
        width: 104px; // 退格键宽度是两个按钮+间距
        background: #f56c6c;
        color: white;
        font-size: 14px;

        &:hover {
          background: #f78989;
        }
      }
    }
  }

  // 搜索行样式
  .search-row {
    padding-left: 17px;
    .table-cell {
      border-right: none;
    }

    .search-input {
      :deep(.el-input__wrapper) {
        background-color: transparent;
        box-shadow: none;
        border-radius: 4px;
      }

      :deep(.el-input__inner) {
        font-weight: 500;

        &::placeholder {
          font-weight: normal;
        }
      }

      :deep(.el-input__prefix) {
        color: #f87171;
      }
    }
  }

  // 搜索键盘样式
  .search-keyboard {
    position: absolute;
    top: -250px; // 显示在输入框上方，增加高度容纳指示器
    left: 0;
    z-index: 9999;
    background: #f8f9fa;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
    width: 600px;
    max-width: 90vw;

    // 键盘模式指示器
    .keyboard-mode-indicator {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12px;
      padding: 8px 12px;
      background: white;
      border-radius: 6px;
      border: 1px solid #e4e7ed;

      .mode-text {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
      }

      .mode-badge {
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
        color: white;

        &.mode-english {
          background: #409eff;
        }

        &.mode-chinese {
          background: #67c23a;
        }

        &.mode-symbols {
          background: #e6a23c;
        }
      }
    }

    .keyboard-row {
      display: flex;
      gap: 6px;
      margin-bottom: 8px;
      justify-content: center;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .key-btn {
      min-width: 45px;
      height: 40px;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      background: #ffffff;
      color: #333;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 8px;

      &:hover {
        background: #e9ecef;
        border-color: #409eff;
      }

      &:active {
        background: #dee2e6;
        transform: scale(0.95);
      }

      &.delete-btn {
        color: rgb(0, 0, 0);
        min-width: 60px;
      }

      &.clear-btn {
        color: rgb(0, 0, 0);
        min-width: 60px;
      }

      &.switch-btn {
        color: rgb(0, 0, 0);
        min-width: 60px;
      }

      &.space-btn {
        min-width: 60px;
        color: rgb(0, 0, 0);
      }
    }
  }

  // 搜索结果样式
  .search-results {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    z-index: 9998;
    background: white;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    margin-top: 4px;
    max-height: 300px;
    overflow-y: auto;
    width: 100%;

    // 重写搜索结果中的表头样式，确保与内容对齐
    .table-header {
      .header-cell {
        text-align: left !important;
        justify-content: flex-start !important;
      }
    }

    .search-result-item {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #f5f7fa;
      cursor: pointer;
      text-align: left;
      transition: background-color 0.2s;
      height: 48px; // 设置固定高度

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f0f9ff;
      }

      // 清除子元素样式，使用内联样式控制
      .result-name,
      .result-category,
      .result-spec,
      .result-price {
        display: flex;
        align-items: center;
        height: 100%;
        font-size: 14px;
        color: #333;
      }

      .result-category,
      .result-spec {
        font-size: 12px;
        color: #666;
      }

      .result-price {
      }
    }
  }
}
::deep(.el-button) {
  margin: 0px !important;
}
.sickness-page-form {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .sickness-page-form-right {
    margin-left: auto;
  }
}
.delete-button {
  position: absolute;
  right: -17px;
  top: 60%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #989898;
  border-radius: 50%;
  cursor: pointer;
  opacity: 0;
  visibility: hidden;

  transition: all 0.3s ease;
  z-index: 10;

  &:hover {
    transform: translateY(-50%) scale(1.1);
  }

  img {
    width: 16px;
    height: 16px;
    filter: brightness(0) invert(1); // 将图标变为白色
  }
}
::v-deep(.el-input__wrapper) {
  padding-left: 5px !important;
  padding-right: 5px !important;
}
</style>
<style lang="scss">
.custom-transition-dialog {
  padding: 0 !important;
  .el-dialog__header {
    display: none;
  }
}
</style>
